package com.siecom.algorithm.aes;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;


import com.siecom.tool.LogUtil;

import java.util.Locale;
import java.util.Map;

public class KeyInfoUtil {
   private static final String TAG = "KeyInfoUtil";
   private final SharedPreferences sp;
   private static byte[] key;
   private static byte[] iv;

   public KeyInfoUtil(Context context){
      sp = context.getSharedPreferences("sie_key_info", Context.MODE_PRIVATE);
      byte[] bytes = context.getPackageName().getBytes();
      if (null == key || null == iv) {
         key = new byte[16];
         System.arraycopy(bytes, 0, key, 0, Math.min(key.length, bytes.length));

         bytes = this.getClass().getSimpleName().getBytes();
         iv = new byte[16];
         System.arraycopy(bytes, 0, iv, 0, Math.min(iv.length, bytes.length));
      }
   }

   public String getMainKeyName(int index){
      return String.format(Locale.CHINESE, "mk_%d", index);
   }

   /**
    * 获取工作密钥名称
    * @param keyType  1 pinKey  2 workKey  3 macKey 4 signKey
    * @param wIndex 索引
    * @return wk_1_1
    */
   public String getWorkKeyName(int keyType, int wIndex){
      return String.format(Locale.CHINESE, "wk_%d_%d", keyType, wIndex);
   }

   public void saveKey(String name, String value){
      value = AESUtils.encrypt(key, iv, value);
      sp.edit().putString(name, value).apply();
   }

   public String getKey(String name){
      String value = sp.getString(name, "");
      value = AESUtils.decrypt(key, iv, value);
      return value;
   }

   public void clearKeyInfo(){
      Map<String, ?> map = sp.getAll();
      if(map.isEmpty()) return;
      SharedPreferences.Editor edit = sp.edit();
      for (String s : map.keySet()) {
         if(TextUtils.equals(s, "tusn")) continue;
         edit.remove(s);
      }
      edit.apply();
   }


}
